#!/usr/bin/env python
#-*- coding:utf-8 -*-

import logging
from shorp.core.interpreter import *
from shorp.shorp import Shorp

VERSION = '20100408'
logger = logging.getLogger('shorp.xmlinterpreter')

class RuleInterpreter(Interpreter):
    root = Node()
    
    def __init__(self, rule):
        shorp = Shorp()
        shorp.add(rule)
        self.rule = shorp.parse()
        #print self.rule
    
    def matchrule(self, name):
        rules = self.rule.getChilds()
        for r in rules:
            if r.getAttr('+') == name:
                return r
        return self.matchrule('')    # get default rule
        
    def interpret(self, node, intent=-1):
        if intent<0:
            rule = self.root
            ruletpl = ''
        else:
            rulename = node.getAttr('+')
            rule = self.matchrule(rulename)
            ruletpl = rule.getAttr(':')
        
        return getattr(self, 'rule_%s'%ruletpl)(node, rule, intent)
    
    def rule_(self, node, rule, intent):
        text = rule.getScript()
        childs = node.getChilds()
        
        if text == '':
            for child in childs:
                text += self.interpret(child, intent+1)        
        return text

class XmlInterpreter(RuleInterpreter):
    
    def rule_xml(self, node, rule, intent):
        element = rule.getAtAttr(0)
        if element == '':
            element = rule.getAttr('+')
            
        attrstxt = ""       
        elestxt = ""    
        
        # apply attr rules        
        attrrules = rule.getChilds()
        for i in range(len(attrrules)):
            attrrule = attrrules[i]
            key =  attrrule.getAttr('+')
            value = node.getAttr(key)
            if value == '':
                value = node.getAtAttr(i)
            if value == '':
                if attrrule.getAttr('.') == 'script':
                    value = node.getScript()
            
            tpl = attrrule.getAttr(':')
            if tpl == 'attr':
                attrstxt += ' %s="%s"'%(key, value)
            elif tpl == 'text':
                elestxt = value
        
        # find childs for sub element contents
        childs = node.getChilds()   
        for child in childs:
            elestxt += self.interpret(child, intent+1)
        
        cls = rule.getAttr('.')
        if element == "":
            xml = self.intent(intent) + "%s\n"%elestxt        
        elif cls == "noele":
            xml = self.intent(intent) + "<%s%s />\n"%(element, attrstxt)
        elif cls == "textonly":
            xml = (self.intent(intent) + "<%s%s>%s" + "</%s>\n")%(element, attrstxt, elestxt, element)
        else:
            xml = (self.intent(intent) + "<%s%s>\n%s" + "</%s>\n")%(element, attrstxt, elestxt, element)
        
        return xml
        